const Seller = require('../model/Seller');
const Buller = require('../model/Buller');
const Good = require('../model/Good');
const Follow = require('../model/Follow');
const Like = require('../model/Likes');
const Ding = require('../model/Ding');
//验证模块
const validator = require('validator');
//db中有增加数据方法
const DbSet = require('../model/db');
const setting = require('../setting');
const auth = require('../common/auth');
const mail = require('../common/mail');
const multer = require('multer');

exports.regist = function (req, res, next) {

    var uname = req.body.uname;
    var pwd = req.body.pwd;
    var phone = req.body.phone;
    var email = req.body.email;

    var error = ''
    if (!validator.matches(uname, /^[a-zA-Z0-9\-\.\+\*_ \u4e00-\u9fa5]{3,9}$/)) {
        error = '账号为3-11位'
    }
    if (!validator.matches(pwd, /^[a-zA-Z0-9\-\.\+\*_\@\#\!\?\$]{6,12}$/, 'g')) {
        error = '密码不合法，长度为5-11';
    }
    if (!validator.matches(phone, /^\d{11}$/)) {
        error = '电话不合法，长度为11';
    }
    if (!validator.isEmail(email)) {

        error = '邮箱不合法'

    }
    if (error) {
        return res.end(error);
    }

    Seller.getSellerByName(uname, function (err, seller) {

        if (err) {
            return res.end(err);
        }
        if (seller) {
            return res.end('该用户名已注册');
        }
        Seller.getSellerByEmail(email, function (err, seller1) {
            if (err) {
                return res.end(err);
            }
            if (seller1) {
                return res.end('该邮箱已注册');
            }

            Seller.getSellerByPhone(phone, function (err, seller2) {
                if (err) {
                    return res.end(err);
                }
                if (seller2) {
                    return res.end('该手机已注册');
                }
                let newPwd = DbSet.encrypt(pwd, setting.PSDkey);
                req.body.pwd = newPwd;
                let reqMsg = {
                    name: uname,
                    email: email
                }
                console.log(req.body);
                mail.sendMails(reqMsg, function (err, info) {
                    if (err) {
                        console.log('邮件发送失败！');
                    }
                })

                DbSet.addOne(req, res, Seller, req.body);

            })


        })


    })


}
exports.login = function (req, res, next) {

    var uname = req.body.uname;
    var pwd = req.body.pwd;
    var isName = '';


    if (validator.matches(uname, /^[a-zA-Z0-9\-\.\+\*_ \u4e00-\u9fa5]{3,9}$/)) {
        isName = Seller.getSellerByName;
    }
    if (validator.isEmail(uname)) {
        isName = Seller.getSellerByEmail;
    }
    if (validator.matches(uname, /^\d{11}$/)) {
        isName = Seller.getSellerByPhone;
    }

    if (isName !== '') {


        isName(uname, function (err, seller) {

            if (err) {
                return res.end(err);
            }
            if (!seller) {
                return res.end('该用户不存在');
            }
            if(seller.isDis == true){
                return res.end('该账号已被封禁');
            }

            var newPwd = DbSet.encrypt(pwd, setting.PSDkey);

            if (newPwd == seller.pwd) {

                auth.create_cookie(seller, res);
                return res.json({msg: 'success', seller, categorys: setting.categorys});


            }
            res.end('密码错误！')


        })

    } else {
        return res.end('格式错误');
    }


}
exports.checkLogin = function (req, res, next) {


    if (req.session.seller) {
// //         console.log('登陆中')
//
// //
        var id = req.session.seller._id;
        Seller.getSellerById(id, function (err, seller) {
            if (err) {
                return res.end(err);
            }

            res.json({error: 0, data: seller, cates: setting.categorys});

        })


    } else {

        res.json({error: 1, data: null,cates: setting.categorys});
    }


}
exports.out = function (req, res, next) {
    req.session.seller = null;
    res.clearCookie(setting.auth_cookie_name); // 清空cookie
    req.session.sellerLogin = false;
    res.json({err: 0, msg: 'success'});
}


exports.addGoods = function (req, res, next) {
    if (!req.session.seller) {
        return res.end(null);
    }
    req.body.king_id = req.session.seller._id;
    req.body.avatar = req.body.avatar.slice(9, req.body.avatar.length - 1);
    req.body.avatar = req.body.avatar.split(',');
    var c = [];
    var d = [];
    for(key in req.body){

        if(key.indexOf('color')>=0){
            c.push(req.body[key]);
        }
        if(key.indexOf('model')>=0){
            d.push(req.body[key]);
        }
    }
    req.body.color = c;
    req.body.model = d;


    Seller.getSellerById(req.body.king_id, (err, seller) => {
        if (err) {
            return res.end(err);
        }
        seller.score += 10;
        seller.shopNum += 1;
        req.session.seller = seller;
        seller.save();
        console.log(seller.score);
        var newGood = new Good(req.body);
        newGood.save().then(function (result) {
            res.json({msg: 'success'});
        }).catch(function (err) {
            res.end(err);
            console.log(err);
        })

    })


}
exports.changeInfo = (req, res, next) => {
    var id = req.session.seller._id;

    for(key in req.body){
        if(req.body[key]==''){
            delete  req.body[key];
        }
    }

    Seller.updateSeller(id, req.body, (err, seller) => {

        if (err) {
            return res.end(err);
        }

        Seller.getSellerById(id, (err, data) => {

            if (err) {
                return res.end(err);
            }

            res.json({msg: 'success', seller: data});
        })


    })


}


exports.myGoods = (req, res, next) => {
    if (!req.session.seller) {
        return res.end(null);
    }

    var page = parseInt(req.query.page)
    var sheng = req.query.sheng;

    var start = parseInt(req.query.start);
    var end = parseInt(req.query.end);

    console.log(start, end);

    var query;
    if (start || start === 0) {
        query = {'price': {'$gte': start, '$lt': end}}
    } else {
        query = {}
    }

    if (!page) {
        page = 1;
    }
    if (!sheng) {
        sheng = 'true';
    }
    // console.log(page);

    // console.log(sheng);

    if (sheng == 'true') {


        Good.getGoodsByKing(req.session.seller._id, query, (err, d) => {
            // console.log(d)
            // console.log(query)
            if (err) {

                return res.end(err);

            }


            Good.find({
                'king_id': req.session.seller._id,
                deleted: false
            }, query).sort({price: 1}).skip(8 * (page - 1)).limit(8).exec(function (err, data) {
                if (err) {
                    return res.json({
                        err: 1,
                        mes: err.toString()
                    });
                }

                if (data.length <= 0) {

                    if (req.session.seller) {
                        return res.json({error: 0, msg: '收到了', data, user: req.session.seller})
                    } else {
                        return res.json({error: 0, msg: '收到了', data, user: null})
                    }

                }

                if (req.session.seller) {
                    res.json({error: 0, msg: '收到了', data, user: req.session.seller})
                } else {
                    res.json({error: 0, msg: '收到了', data, user: null})
                }

            })

        })


    }
    if (sheng == 'false') {

        Good.getGoodsByKing(req.session.seller._id, query, (err, d) => {
            // console.log(query);
            // console.log(d)
            if (err) {

                return res.end(err);

            }


            Good.find({
                'king_id': req.session.seller._id,
                deleted: false
            }, query).sort({price: -1}).skip(8 * (page - 1)).limit(8).exec(function (err, data) {
                if (err) {
                    return res.json({
                        err: 1,
                        mes: err.toString()
                    });
                }

                if (data.length <= 0) {

                    if (req.session.seller) {
                        return res.json({error: 0, msg: '收到了', data, user: req.session.seller})
                    } else {
                        return res.json({error: 0, msg: '收到了', data, user: null})
                    }

                }

                if (req.session.seller) {
                    res.json({error: 0, msg: '收到了', data, user: req.session.seller})
                } else {
                    res.json({error: 0, msg: '收到了', data, user: null})
                }

            })

        })


    }


}





exports.sellerGoods = (req, res, next) => {


    var page = parseInt(req.query.page)
    var sheng = req.query.sheng;

    var start = parseInt(req.query.start);
    var end = parseInt(req.query.end);

    var id = req.query.seller_id;

    var query;
    if (start || start === 0) {
        query = {'price': {'$gte': start, '$lt': end}}
    } else {
        query = {}
    }

    if (!page) {
        page = 1;
    }
    if (!sheng) {
        sheng = 'true';
    }
    // console.log(page);

    // console.log(sheng);

    if (sheng == 'true') {


        Good.getGoodsByKing(id, query, (err, d) => {
            // console.log(d)
            // console.log(query)
            if (err) {

                return res.end(err);

            }


            Good.find({
                'king_id': id,
                deleted: false
            }, query).sort({price: 1}).skip(8 * (page - 1)).limit(8).exec(function (err, data) {
                if (err) {
                    return res.json({
                        err: 1,
                        mes: err.toString()
                    });
                }

                if (data.length <= 0) {

                    if (req.session.seller) {
                        return res.json({error: 0, msg: '收到了', data, user: req.session.seller})
                    } else {
                        return res.json({error: 0, msg: '收到了', data, user: null})
                    }

                }

                if (req.session.seller) {
                    res.json({error: 0, msg: '收到了', data, user: req.session.seller})
                } else {
                    res.json({error: 0, msg: '收到了', data, user: null})
                }

            })

        })


    }
    if (sheng == 'false') {

        Good.getGoodsByKing(id, query, (err, d) => {
            // console.log(query);
            // console.log(d)
            if (err) {

                return res.end(err);

            }


            Good.find({
                'king_id': id,
                deleted: false
            }, query).sort({price: -1}).skip(8 * (page - 1)).limit(8).exec(function (err, data) {
                if (err) {
                    return res.json({
                        err: 1,
                        mes: err.toString()
                    });
                }

                if (data.length <= 0) {

                    if (req.session.seller) {
                        return res.json({error: 0, msg: '收到了', data, user: req.session.seller})
                    } else {
                        return res.json({error: 0, msg: '收到了', data, user: null})
                    }

                }

                if (req.session.seller) {
                    res.json({error: 0, msg: '收到了', data, user: req.session.seller})
                } else {
                    res.json({error: 0, msg: '收到了', data, user: null})
                }

            })

        })


    }


}












exports.remove = (req, res, next) => {

    var id = req.query.id;
    Good.removeOne(id, (err, good) => {

        if (err) {
            return res.end(err);
        }

        res.end('success');


    })


}
exports.change = (req, res, next) => {
    var id = req.query.id;
    Good.getGoodById(id, (err, good) => {
        if (err) {
            return res.end(err);
        }
        Good.find({deleted: false, changeNow: true,'king_id':req.session.seller._id}).exec(function (err, data) {
            if (err) {
                return res.end(err)
            }

            if(data.length == 1 && data[0]._id == id){

                return res.end('success');

            }


            if (data.length > 0) {
                data.forEach(function (item, ins) {
                    item.changeNow = false;
                    item.save();

                })

                good.changeNow = true;
                good.save();
                res.end('success');

            } else {
                good.changeNow = true;
                good.save();
                res.end('success');
            }

        })


    })

}
exports.checkNewGood = (req,res,next)=>{

    Good.getGood({'changeNow':true,'king_id':req.session.seller._id},(err,good)=>{
        if(err){
            return res.end(err);
        }
        res.json({msg:'success',data:good});
    })


}
exports.changeForm = (req,res,next)=>{

    console.log(req.body);
    var id = req.body.good_id;
    for(key in req.body){
        if(req.body[key]==''){
            delete  req.body[key];
        }
    }
    Good.getGoodById(id,(err,good)=>{
        if(err){
            return res.end(err);
        }
        Good.updateById(id,req.body,(err,good)=>{

            if(err){
                return res.end(err);
            }
            res.json({msg:'success',good})
        })
    })

}


exports.like = (req,res,next)=>{

    if(!req.session.buller){
        return res.end('fail');
    }
    var seller_id = req.query.seller_id;

    var king_id = req.session.buller._id;


    Seller.getSellerById(seller_id,(err,seller)=>{
        if(err){
            return res.end(err);
        }

        Follow.getFollowById(seller_id,king_id,(err,follow)=>{
            if(err){
                return res.end(err);
            }
            if(follow){

                Follow.findOneAndRemove({'_id':follow._id}).exec((function (err,data) {
                    console.log(data)
                }));
                seller.follows -= 1;
                seller.save();

            }else{
                var follow = new Follow({
                    store_id:seller_id,
                    king_id
                })
                follow.save();
                seller.follows += 1;
                seller.save();
            }
            res.json({msg:'success',seller});


        })


    })








}
exports.getInfo = (req,res,next)=>{
    var id = req.query.seller_id;
    Seller.getSellerById(id, function (err, seller) {
        if (err) {
            return res.end(err);
        }

        res.json({error: 0, data: seller});

    })


}



exports.noSend = (req,res,next)=>{

    if(!req.session.seller){
        return res.end('fail');
    }
    var page = parseInt(req.query.page)
    if(!page){
        page = 1;
    }


    Ding.getDingsBySeller({'seller_id':req.session.seller._id,'money':true,'hasSend':false},(err,data)=>{
        if (err) {
            return res.end(err);
        }
        Ding.find({'seller_id':req.session.seller._id,'hasSend':false,'money':true})
            .populate('good_id').populate('king_id').sort({'create_time':-1}).skip(6*(page-1)).limit(6).exec(function (err,dings) {

            if(err){
                return res.end(err);
            }

            res.json({dings,count:data.length});


        })



    })


}


exports.sendDing = (req,res,next)=>{
    if(!req.session.seller){
        return res.end('fail');
    }
    var page = parseInt(req.query.page)
    if(!page){
        page = 1;
    }
    var id = req.query.id;
    console.log(id);
    Ding.getDingById(id,(err,ding)=> {
        if (err) {
            return res.end(err);
        }
        var page =1;
        ding.hasSend = true;
        ding.save().then((ding)=>{


            Ding.getDingsBySeller({'seller_id':req.session.seller._id,'money':true,'hasSend':false},(err,data)=>{
                if (err) {
                    return res.end(err);
                }



            Ding.find({'seller_id':req.session.seller._id,'hasSend':false,'money':true}).populate('king_id good_id').sort({'create_time':-1}).skip(6*(page-1)).limit(6).exec(function (err,dings) {

                if(err){
                    return res.end(err);
                }

                res.json({dings,count:data.length});


            })


            })


        })


    })



}
